package com.et.machine.store

import android.content.Context
import android.os.Environment
import android.util.Log
import androidx.annotation.IntDef
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import com.et.logger.TAGS
import java.io.File

@Database(entities = [OutGoodsRecordEntity::class, ChannelEntity::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
    abstract fun outGoodsFlagDao(): IOutGoodsFlagDao
    abstract fun channelDao(): IChannelDao
}

const val IDLE = 0
const val NORMAL = 1
const val DIR_LESS = 2
const val DIR_NOT_EXIST = 3

@Retention(value = AnnotationRetention.SOURCE)
@Target(
    AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY, AnnotationTarget.VALUE_PARAMETER,
    AnnotationTarget.TYPE
)
@IntDef(IDLE, NORMAL, DIR_LESS, DIR_NOT_EXIST)
annotation class DataBaseStatus

object DataBaseUtil {

    @DataBaseStatus
    private var code: Int = IDLE
    var database: AppDatabase? = null

    data class IChannelDaoBox<T : BaseDao>(var dao: T? = null)

    fun channelDao(box: IChannelDaoBox<IChannelDao>): @DataBaseStatus Int {
        if (code == NORMAL) {
            box.dao = database?.channelDao()
        }
        logDatabaseStatus("channelDao")
        return code
    }

    private fun logDatabaseStatus(s: String) {
        Log.d(
            TAGS.vending, "vending:$s dataBase init status:" + (when (code) {
                NORMAL -> "OK"
                IDLE -> "IDLE"
                DIR_LESS -> "DIR_LESS"
                DIR_NOT_EXIST -> "DIR_NOT_EXIST"
                else -> "UNKNOWN"
            })
        )
    }

    @Synchronized
    fun init(ctx: Context): @DataBaseStatus Int {
        if (code == NORMAL) return NORMAL
        Environment.getExternalStoragePublicDirectory("database").apply {
            if (!this.exists()) this.mkdir()
            if (!this.exists()) return DIR_NOT_EXIST.also { code = it }
            val file = File(this, "et-database-m1")
            database = Room.databaseBuilder(
                ctx, AppDatabase::class.java, file.absolutePath
            ).build()
            return NORMAL.also { code = it }
        }
    }

    fun release() {
        if (code == NORMAL) database?.close()
        code = IDLE
    }

}



